import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
@SuppressWarnings("serial")

public class StudentUI extends JFrame
{
	JButton btnAuthorSearch, btnTitleSearch,btnSignOut, btnViewAll;//newbutton is for title search
	Color color1;
	JList bookList, authList;
	DefaultListModel model, model2;//model 1 for book list, model 2 for author list
	JPanel panel,panel2,panel3,panel4;
	JTextField textfield1,textfield2;
	String stra1,title11,author11;
	JLabel alertLabel;//tells user what to do...also tells them what goes wrong.
	JProgressBar progress1=new JProgressBar();//excluded this originally, but it's important to search function. WHY??!!
	int find;
	private JPanel checkInOutPanel;
	private JButton btnCheckOut;
	private JButton btnPreview;
	private JLabel lblStatus;
	private JLabel lblIssue;
	private JPanel panel_1;
	private JPanel panelCover;
	private JLabel lblPublication;
	private JPanel panel_2;
	private JLabel imageLabel;

	private int _curUser = -1;
	//----------------------------------------------------------------------------------------------------
	//      Creating a new sqlAPI
	//----------------------------------------------------------------------------------------------------
	sqlAPI look = new sqlAPI();
	@SuppressWarnings("rawtypes")
	public StudentUI(int cUser)
	{
		super();
		_curUser = cUser;

		color1=new Color(200,255,255);

		getContentPane().setLayout(new BorderLayout());
		setBackground(color1);

		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT){
			private final int location = 200;
			{
				setDividerLocation( location );
			}
			@Override
			public int getDividerLocation() {
				return location ;
			}
			@Override
			public int getLastDividerLocation() {
				return location ;
			}
		};

		getContentPane().add(splitPane, BorderLayout.CENTER);

		panel = new JPanel();
		panel.setBackground(new Color(0, 128, 128));
		splitPane.setLeftComponent(panel);
		panel.setLayout(new BorderLayout(0, 0));

		panel2 = new JPanel();
		panel2.setBackground(new Color(0, 128, 128));
		panel.add(panel2, BorderLayout.NORTH);
		panel2.setLayout(new GridLayout(5, 0, 0, 0));

		btnSignOut = new JButton("Sign Out");
		btnSignOut.setBackground(new Color(0, 128, 128));
		btnSignOut.addActionListener(new ButtonListener());
		panel2.add(btnSignOut);

		btnAuthorSearch = new JButton("Author Search");
		btnAuthorSearch.setBackground(new Color(0, 128, 128));
		panel2.add(btnAuthorSearch);
		btnAuthorSearch.addActionListener(new ButtonListener());

		btnTitleSearch = new JButton("Title Search");
		btnTitleSearch.setBackground(new Color(0, 128, 128));
		panel2.add(btnTitleSearch);
		btnTitleSearch.addActionListener(new ButtonListener());

		btnViewAll = new JButton("View All");
		btnViewAll.setBackground(new Color(0, 128, 128));
		panel2.add(btnViewAll);
		btnViewAll.addActionListener(new ButtonListener());

		alertLabel=new JLabel("Click on a book to view details!");
    alertLabel.setBackground(new Color(143,188,143));
		panel2.add(alertLabel);

		panel3=new JPanel();
		panel3.setLayout(new GridLayout(1,3));

		model=new DefaultListModel();
		bookList = new JList(model);
		bookList.setBackground(new Color(143, 188, 143));
		bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		bookList.addListSelectionListener(new SharedListSelectionHandler());
		panel3.add(bookList);

		model2 = new DefaultListModel();
		authList = new JList(model2);
		authList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		authList.addListSelectionListener(new SharedListSelectionHandler());
		authList.setBackground(new Color(50,116,141));
		panel3.add(authList);

		panel.add(panel3, BorderLayout.CENTER);

		panelCover = new JPanel();
		panelCover.setForeground(new Color(0, 139, 139));
		splitPane.setRightComponent(panelCover);
		panelCover.setLayout(new BorderLayout(0, 0));

		JPanel viewPanel = new JPanel();
		panelCover.add(viewPanel);
		viewPanel.setLayout(new BorderLayout(0, 0));

		checkInOutPanel = new JPanel();
		checkInOutPanel.setBackground(new Color(0, 128, 128));
		viewPanel.add(checkInOutPanel, BorderLayout.SOUTH);
		checkInOutPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		btnCheckOut = new JButton("Check Out");
		btnCheckOut.setEnabled(false);//it's grayed out when nothing in the list is selected
		btnCheckOut.addActionListener(new ButtonListener());//the actionListener is triggered when button is clicked. it calls a method that does the thing you want the button to do.
		checkInOutPanel.add(btnCheckOut);

		btnPreview = new JButton("Preview");
		btnPreview.setEnabled(false);
		btnPreview.addActionListener(new ButtonListener());
		checkInOutPanel.add(btnPreview);

		panel_2 = new JPanel();
		panel_2.setBackground(new Color(0, 128, 128));
		viewPanel.add(panel_2, BorderLayout.CENTER);
		panel_2.setLayout(new BorderLayout(0, 0));

		JPanel detailPanel = new JPanel();
		panel_2.add(detailPanel, BorderLayout.SOUTH);
		detailPanel.setBackground(new Color(95,158,60));

		lblPublication = new JLabel("Publication:       ");
		detailPanel.add(lblPublication);

		lblIssue = new JLabel("Issue:       ");
		detailPanel.add(lblIssue);

		lblStatus = new JLabel("Status:        ");
		detailPanel.add(lblStatus);//;

		ImageIcon myPicture = new ImageIcon("/test_img/15_portrait.jpg");
		imageLabel = new JLabel();
		imageLabel.setIcon(myPicture);

		panel_2.add(imageLabel, BorderLayout.CENTER);
		//desktopPane.add(bookInfo, BorderLayout.EAST);//
		//-------------------------------------------------------------------------------------
		//                                                              TESTED: WORKS!
		//-------------------------------------------------------------------------------------
		try//populate Lists with all books and associated authors(bookList and authList).
		{
			popList();
		}
		catch(Exception der){ 
		  // alertLabel.setText("172:Error Occurs: \n"+der);
			System.out.println("adding all books failed problem");
			der.printStackTrace();
		}
		//--------------------------------------------------------------------------------------
	}// end studentUI

	private class SharedListSelectionHandler implements ListSelectionListener//triggers when a book TITLE is selected from list. Selecting an author does nothing for now
	{
		public void valueChanged(ListSelectionEvent arg0) 
		{//when book in list is selected, in right panel book cover and option to check the book out or in made available
			int j;
			ResultSet allBooks =  look.getAllBooks(); // new table with all the books
			if(arg0.getSource() == authList){
				try{
					j = authList.getSelectedIndex();
					/*System.out.println("selected index is: " + j);
                                        int bookSize = 0;
                                        while(allBooks.next()) {
                                                bookSize++;
                                                System.out.println(allBooks.getInt("book_id"));
                                        }
                                        System.out.println("Resultset: " + bookSize );*/
					allBooks.absolute( (j+1) ); // sets to book row that user selected
					bookList.setSelectedIndex(j); // select the same author as selected book
					String pub = allBooks.getString("publisher");
					String issue = allBooks.getString("issue_date");
					String status = "Checked Out";// set to checked out by default
					//---------------------------------------------------------------------------------------
					//              Trigger labels to show publication info, etc
					//---------------------------------------------------------------------------------------
					lblPublication.setText("Publication: "+pub);///publication information from selected book
					lblIssue.setText("Issue: "+issue); //issue information from selected book;

					boolean isChecked = look.isBookOut(allBooks.getInt("book_id"));
					if(!isChecked){// set status 
						status = "Available";
						btnCheckOut.setEnabled(true);
					} else {
						btnCheckOut.setEnabled(false);
					}
					btnPreview.setEnabled(true);

					lblStatus.setText("Status: "+status);///return date information for selected book.
					//---------------------------------------------------------------------------------------
					//              Trigger image to show in image pane --- this is broken :\
					//---------------------------------------------------------------------------------------
					try {
						String isThere = allBooks.getString("cover");
						ImageIcon bookPic;
						if(isThere == null){
							bookPic =new ImageIcon("test-img/15.JPG");	
						}
						else{
							bookPic = new ImageIcon(allBooks.getString("cover"));
						}
						imageLabel.setIcon(bookPic);
						imageLabel.setHorizontalTextPosition(JLabel.CENTER);
					} catch (Exception e) { 
						//alertLabel.setText("227:Error: "+e);
						e.printStackTrace();
					}
				}
				catch(Exception del){
					del.printStackTrace();
				}
			}
			else{
				try{
					j = bookList.getSelectedIndex();
					allBooks.absolute( (j+1) ); // sets to book row that user selected
					authList.setSelectedIndex(j); // select the same author as selected book
					String pub = allBooks.getString("publisher");
					String issue = allBooks.getString("issue_date");
					String status = "Checked Out";// set to checked out by default
					//---------------------------------------------------------------------------------------
					//                      Trigger labels to show publication info, etc
					//---------------------------------------------------------------------------------------
					lblPublication.setText("Publication: "+pub);///publication information from selected book
					lblIssue.setText("Issue: "+issue); //issue information from selected book;

					boolean isChecked = look.isBookOut(allBooks.getInt("book_id"));
					if(!isChecked){// set status 
						status = "Available";
					}
					lblStatus.setText("Status: "+status);///return date information for selected book.
					//---------------------------------------------------------------------------------------
					//                      Trigger image to show in image pane --- this is broken :\
					//---------------------------------------------------------------------------------------
					try {
						String isThere = allBooks.getString("cover");
						ImageIcon bookPic;
						if(isThere == null){
							bookPic =new ImageIcon("/home/project/webswing-1.1/test-img/15_portrait");	
						}
						else{
							bookPic = new ImageIcon(allBooks.getString("cover"));
						}
						imageLabel.setIcon(bookPic);
						imageLabel.setHorizontalTextPosition(JLabel.CENTER);
					} catch (Exception e) { 
						alertLabel.setText("245:Error: "+e);
						e.printStackTrace();
					}
				}
				catch(Exception ef){
					ef.printStackTrace();
				}
			}
		}
	}// end of handler

	private class ButtonListener implements ActionListener//when buttons are pressed
	{
		public void actionPerformed(ActionEvent event)//event source is button
		{
			//----------------------------------------------------------------------------------------------------
			//                                                      Author Search Starts HERE!!!!!
			//----------------------------------------------------------------------------------------------------
			//                                                      Tested working.
			//----------------------------------------------------------------------------------------------------
			if(event.getSource()==btnAuthorSearch)
			{
				String want = JOptionPane.showInputDialog("Enter an Author Name");
				ResultSet srcRes = look.searchAuthor(want);

				if(want==null)
				{
					alertLabel.setText("I guess you didn't want to Search afterall");
					popList();
				} else {
					model.clear();
					model2.clear();
					try{
						if(srcRes.next()) {                     
							do{
								// get dat book!
								String bookNameX = srcRes.getString("title");
								model.addElement(bookNameX);
								// love dat auth...or!
								String authNameX = srcRes.getString("author_last_name");
								model2.addElement(authNameX);
							} while(srcRes.next());
						} else {
							model.addElement("No Match");
							model2.addElement("No Match");  
						}
					} catch (Exception e) {
						System.out.println("Author Search bit it.");
						e.printStackTrace();
					}
				}
				//search, repopulate book lists with possible book variable "want" is the search term
				/*try{
                                        model.removeAllElements();// mo1-5 are default list models//books these line removes all elements from the lists. 
                                        model2.removeAllElements();// The search results replace them
                                        if(!want.equals("")){
                                                int booksFound = 0;
                                                allBooks.last();
                                                int dBSize = allBooks.getRow()+10; // total size of dB
                                                for(int k=0;k<want.length();k++){
                                                        char ch=want.charAt(k);
                                                        stra1=stra1+ch;
                                                }//every character of what user input is placed into it's own string
                                                for(int v=1;v<dBSize;v++){// need to do this for each book.
                                                        author11="";
                                                        allBooks.absolute(v);
                                                        String author = allBooks.getString("author_last_name");
                                                        find=v;
                                                        try{
                                                                for(int z=0;z<want.length();z++)
                                                                {
                                                                        author11=author11+author.charAt(z);
                                                                }
                                                        }
                                                        catch(Exception def){
                                                                alertLabel.setText("299:Error"+def);
                                                        }                                                                                       
                                                        if(author.toLowerCase().equals(want)||author.toUpperCase().equals(want)){
                                                                // We found a book
                                                                        booksFound++;
                                                                        allBooks.absolute(find);
                                                                        model.addElement(allBooks.getString("title")+"");
                                                                        model2.addElement(allBooks.getString("author_last_name")+"");
                                                        }
                                                        else if(author11.toLowerCase().equals(want)|| author11.toUpperCase().equals(want)){
                                                                // We found a book
                                                                booksFound++;
                                                                allBooks.absolute(find);
                                                                model.addElement(allBooks.getString("title")+"");
                                                                model2.addElement(allBooks.getString("author_last_name")+"");
                                                        }
                                                }// end dBsize for
                                                alertLabel.setText("Total Books Found: "+booksFound);                                                   
                                        }// end if
                                        else{
                                                try{//populate Lists with all books and associated authors(bookList and authList).
                                                        allBooks.absolute(1);// sets to the start of the rs
                                                        String bookNameX = "";
                                                        String authNameX = "";
                                                        int i = -1;

                                                        // While loop checks the position of the resultset row int
                                                        // and breaks as soon as we hit the last item in the table
                                                        while(!allBooks.isAfterLast()){
                                                                i = allBooks.getRow();
                                                                // get dat book!
                                                                bookNameX = allBooks.getString("title");
                                                                model.addElement(bookNameX);
                                                                // love dat auth...or!
                                                                authNameX = allBooks.getString("author_last_name");
                                                                model2.addElement(authNameX);
                                                                allBooks.next();// itterate to the next book
                                                        }
                                                alertLabel.setText("Click on a book to view details!");
                                                }
                                                catch(Exception der){ 
                                                       // alertLabel.setText("340:Error Occurs: \n"+der);
                                                        System.out.println("adding all books failed problem");
                                                        der.printStackTrace();
                                                }
                                        }
                                }// end try
                                catch (Exception der) {
                                      //  alertLabel.setText("345:Error" + der);
                                } */
			}
			//----------------------------------------------------------------------------------------------------
			//                      Title Search Starts HERE!!!!!!
			//----------------------------------------------------------------------------------------------------
			else if(event.getSource()==btnTitleSearch)//title search
			{

				String want=(String)JOptionPane.showInputDialog("Enter A Book Title");

				ResultSet srcRes = look.searchTitle(want);

				//search, repopulate book list with possible books
				if(want==null)
				{
					alertLabel.setText("I guess you didn't want to Search afterall");
					popList();
				} else {
					model.clear();
					model2.clear();
					try{
						if(srcRes.next()) {                     
							do{
								// get dat book!
								String bookNameX = srcRes.getString("title");
								model.addElement(bookNameX);
								// love dat auth...or!
								String authNameX = srcRes.getString("author_last_name");
								model2.addElement(authNameX);
							} while(srcRes.next());
						} else {
							model.addElement("No Match");
							model2.addElement("No Match");  
						}
					} catch (Exception e) {
						System.out.println("Book Search bit it.");
						e.printStackTrace();
					}
				}
				/*}
                                else
                                try{

                                        if(!want.equals("")){
               model.removeAllElements();// mo1-5 are default list models//books these line removes all elements from the lists.
                                        model2.removeAllElements();// The search results replace them
                                                int booksFound = 0;
                                                allBooks.last();
                                                int dBSize = allBooks.getRow(); // total size of dB
                                                for(int k=0;k<want.length();k++){
                                                        char ch=want.charAt(k);
                                                        stra1=stra1+ch;
                                                }//every character of what user input is placed into it's own string
                                                for(int v=1;v<dBSize;v++){// need to do this for each book.
                                                        title11="";
                                                        allBooks.absolute(v);
                                                        String title = allBooks.getString("title");
                                                        find=v;
                                                        try{
                                                                for(int z=0;z<want.length();z++)
                                                                {
                                                                        title11=title11+title.charAt(z);
                                                                }
                                                        }
                                                        catch(Exception def){
                                                                alertLabel.setText("382:Error"+def);
                                                        }                                                                                       
                                                        if(title.toLowerCase().equals(want)||title.toUpperCase().equals(want)){
                                                                // We found a book
                                                                        booksFound++;
                                                                        allBooks.absolute(find);
                                                                        model.addElement(allBooks.getString("title")+"");
                                                                        model2.addElement(allBooks.getString("author_last_name")+"");
                                                        }
                                                        else if(title11.toLowerCase().equals(want)|| title11.toUpperCase().equals(want)){
                                                                // We found a book
                                                                booksFound++;
                                                                allBooks.absolute(find);
                                                                model.addElement(allBooks.getString("title")+"");
                                                                model2.addElement(allBooks.getString("author_last_name")+"");
                                                        }
                                                }// end dBsize for
                                                alertLabel.setText("Total Books Found: "+booksFound);                                                   
                                        }// end if
                                        else{
                                                try{//populate Lists with all books and associated authors(bookList and authList).
                                                        allBooks.absolute(1);// sets to the start of the rs
                                                        String bookNameX = "";
                                                        String authNameX = "";
                                                        int i = -1;

                                                        // While loop checks the position of the resultset row int
                                                        // and breaks as soon as we hit the last item in the table
                                                        while(!allBooks.isAfterLast()){
                                                                i = allBooks.getRow();
                                                                // get dat book!
                                                                bookNameX = allBooks.getString("title");
                                                                model.addElement(bookNameX);
                                                                // love dat auth...or!
                                                                authNameX = allBooks.getString("author_last_name");
                                                                model2.addElement(authNameX);
                                                                allBooks.next();// itterate to the next book
                                                        }
                                                alertLabel.setText("Click on a book to view details!");
                                                }
                                                catch(Exception der){ 
                                                        alertLabel.setText("423:Error Occurs: \n"+der);
                                                        System.out.println("adding all books failed problem");
                                                        der.printStackTrace();
                                                }
                                        }
                                }// end try
                                catch(Exception der){
                                        alertLabel.setText("430:Error"+der);
                                }*/
			}
			//----------------------------------------------------------------------------------------------------
			//                      SignOut Starts HERE!!!!!!
			//----------------------------------------------------------------------------------------------------
			if(event.getSource()==btnSignOut)
			{
				setVisible(false);
				removeAll();
				splash1 s = new splash1();
				s.setVisible(true);
				s.setSize(270,180);
				s.setLocation(120,100);
			}
			//----------------------------------------------------------------------------------------------------
			//                      Preview Starts HERE!!!!!!
			//----------------------------------------------------------------------------------------------------
			if (event.getSource()==btnPreview)
			{
				ResultSet allBooks = look.getAllBooks();
				try {
					int id = bookList.getSelectedIndex();
					allBooks.absolute( (id + 1) );
					//System.out.print(id);
					String filePath= allBooks.getString("pdfPath");
					ViewPdf view = new ViewPdf(filePath);
				} catch (SQLException e) {
					//alertLabel.setText("454:Error"+e);
					e.printStackTrace();
				}
				catch (Exception f) {
				  // alertLabel.setText("458:Error"+f);
					f.printStackTrace();
				}
			}
			if(event.getSource()==btnViewAll)
			{
				model.removeAllElements();
				model2.clear();
				popList();
			}
			//----------------------------------------------------------------------------------------------------
			//                      Checkout Starts HERE!!!!!!!!!
			//----------------------------------------------------------------------------------------------------
			if (event.getSource()==btnCheckOut)
			{
				try{
					alertLabel.setText("userId: " + _curUser);
					int selectedBook = bookList.getSelectedIndex();
					int chkStat = look.checkOut(_curUser, (selectedBook + 1));
					switch (chkStat) {
					case -1:
						JOptionPane.showMessageDialog(panel, "Sorry, this book is already checked out.");
						System.out.println("Try to checkout a book marked as Out");
						break;
					default:
						System.out.println("The checkout biffed with err: " + chkStat );
						//alertLabel.setText("Checkout Err: " + chkStat);
						break;
					}
				} catch (Exception e) {
					//alertLabel.setText("Checkout() try Caught");
					e.printStackTrace();
				}
			}

		}
	}// end of actionBtn
	public void popList()//method for populating the list
	{
		try//populate Lists with all books and associated authors(bookList and authList).
		{
			ResultSet allBooks =  look.getAllBooks(); // new table with all the books
			allBooks.absolute(1);// sets to the start of the rs
			String bookNameX = "";
			String authNameX = "";
			int i = -1;

			// While loop checks the position of the resultset row int
			// and breaks as soon as we hit the last item in the table
			while(!allBooks.isAfterLast()){
				i = allBooks.getRow();
				// get dat book!
				bookNameX = allBooks.getString("title");
				model.addElement(bookNameX);
				// love dat auth...or!
				authNameX = allBooks.getString("author_last_name");
				model2.addElement(authNameX);
				allBooks.next();// itterate to the next book
			}
			allBooks.close();
		}
		catch(Exception der){
		  // alertLabel.setText("172:Error Occurs: \n"+der);
			System.out.println("adding all books failed problem");
			der.printStackTrace();
		}
	}
	public ImageIcon resize(ImageIcon ic)
	{
		Image img=ic.getImage();
		Image newImg=img.getScaledInstance(300,400,java.awt.Image.SCALE_SMOOTH);
		ImageIcon newIcon=new ImageIcon(newImg);

		return newIcon;
	}

}// end of class
